#!/bin/bash
APP_PORT=-1
RAND_PORT=-1
ENV=pre_prod
product_app_port(){
	sum=100
	if [ $APP_PORT -ne -1 ];then
		echo "使用指定端口：$APP_PORT"
		num=$(netstat -ntlp | awk '{print $4}' |grep ${APP_PORT} |wc -l)
			if [ $num -ne 0 ];then
				echo "端口被占用，请重新指定端口"
				exit
			else 
				echo "指定端口有效"
				RAND_PORT=$APP_PORT
			fi
	else 
		echo "使用随机生成端口"
		while [ $sum -gt 0 ]
		do
			let sum--
			RAND_PORT=$(rand 8000 9000)
			echo "生成的随机端口：$RAND_PORT"
			#判断端口是否被占用
			num=$(netstat -ntlp | awk '{print $4}' |grep ${RAND_PORT} |wc -l)
			if [ $num -ne 0 ];then
				echo "端口被占用，重新调用rand"
			else 
				echo "端口有效,退出循环"
				break
			fi
			if [ $sum -e 0 ];then
				echo "端口已耗尽，请联系管理员"
			fi
		done
	fi

}
PRE_PROD_IP=$2


build_all(){
	while read line
	do
		APP_NAME=$line
		echo "开始构建$line模块"
		mkdir -p /logs/$ENV/${APP_NAME}
		#找到jar包
		JAR_NAME=$(find /home/jenkins/repo/pre_prod/$APP_NAME -name *.jar)
		
		product_app_port
		echo "最终生成的端口：$RAND_PORT"
		DOCKER_ID=$(docker run -itd -p ${RAND_PORT}:${RAND_PORT} -v /logs/$ENV/${APP_NAME}:/root/logs/ --net host --name  ${ENV}_${APP_NAME}_${RAND_PORT} ${ENV}_${APP_NAME}:latest bash -c "java -jar -Dserver.port=${RAND_PORT} -Xmx256m -Xms256m -Xmn128m /root/target.jar > /root/logs/${APP_NAME}.log")
		
	done < $1
}


echo  "
nms-service
search-service
payment-service
ech-gateway
auth-service
system-service
base-service
cms-service
ech-imc-service
ech-gateway
user-service
pms-service
order-service
bidding-service
workflow-service
mcs-service
finance-service
ech-crm
ech-dzht
ech-erp
ech_notice
ech_finance
ech-jiaofei
" > modules.txt


main(){
	
	build_all modules.txt
}